package com.hjx.service.impl;

import com.hjx.entity.SysRole;
import com.hjx.entity.SysUser;
import com.hjx.entity.SysUserRole;
import com.hjx.mapper.SysUserMapper;
import com.hjx.mapper.SysUserRoleMapper;
import com.hjx.service.SysUserService;
import com.hjx.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 10:44
 */
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysUser findOne(String uno) {
        return sysUserMapper.findOne(uno);
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserMapper.findAll();
    }

    @Override
    public boolean insert(SysUser sysUser) {
        if (sysUser.getPassword() != null && !sysUser.getPassword().equals("")) {
            sysUser.setUid(UUIDUtil.getUUID());
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            boolean result = sysUserMapper.insert(sysUser);
            if (result){
                //为新创建的用户配置用户权限
                sysUserRoleMapper.insertBatch(new SysUserRole()
                        .setUid(sysUser.getUid())
                        .setRids(new HashSet<>(Collections.singletonList("3"))));
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(String uno) {
        return sysUserMapper.delete(uno);
    }

    @Override
    public boolean update(SysUser sysUser) {

        return sysUserMapper.update(sysUser);
    }

    @Override
    public List<SysUser> findBy(SysUser sysUser) {

        return sysUserMapper.findBy(sysUser);
    }

    @Override
    public boolean updateMyself(SysUser sysUser) {
        return sysUserMapper.updateMyself(sysUser);
    }

    @Override
    public String findPassword(String uno) {
        return sysUserMapper.findPassword(uno);
    }

    @Override
    public SysUser findUserAndRole(String uno) {
        if (!StringUtils.isEmpty(uno) && !StringUtils.isBlank(uno)) {
            return sysUserMapper.findUserAndRole(uno);
        }
        return null;
    }

    @Override
    public List<SysUser> findAllUserAndRole() {
        return sysUserMapper.findAllUserAndRole();
    }
//
//    @Override
//    public List<SysRole> findNoGetRoleByUno(String uno) {
//        return sysUserMapper.findNoGetRoleByUno(uno);
//    }
}
